package com.huitone.smspfm.oldclient.asclient.send;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.huitone.smspfm.oldclient.app.AppStaticConfigs;
import com.huitone.smspfm.oldclient.logger.ExtLogger;
import com.huitone.smspfm.oldclient.model.MtSms;
import com.huitone.smspfm.oldclient.store.MtTmpStore;
import com.huitone.smspfm.socket.client.SmsClient;
import com.huitone.smspfm.socket.protocol.sgip.constant.CommandID;
import com.huitone.smspfm.socket.protocol.sgip.constant.Constant;
import com.huitone.smspfm.socket.protocol.sgip.message.Message;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.Submit2;
import com.huitone.smspfm.socket.protocol.sgip.message.msghead.Head;

/**   
* @Title MsgResendTask.java 
* @Package com.huitone.smspfm.oldclient.asclient.send 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年10月13日 下午1:47:05 
* @version V1.0   
*/
public class MsgResendTask extends Thread {
	
	private final static ExtLogger logger = ExtLogger.create(MsgResendTask.class);
	
	private final static long TIME_INTEVAL = 60000; // 重发时间间隔
	
	private boolean toSleep = false;
	private long timeToSleep = 1000;
	
	private SmsClient client = null;
	
	private boolean keepGoing = true;
	
	private ExecutorService fixedThreadPool1 = new ThreadPoolExecutor(AppStaticConfigs.msgSendPoolSize, 
			AppStaticConfigs.msgSendPoolSize, 1L, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), new RejectedExecutionHandler() {
		
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			if (!executor.isShutdown()) {
				try {
					executor.getQueue().put(r);
				} catch (InterruptedException e) {
					logger.error(getClass().getSimpleName()+"fixedThreadPool1　 进程异常");
					e.printStackTrace();
				}
			}
		}
	});
	
	private ExecutorService fixedThreadPool2 = new ThreadPoolExecutor(AppStaticConfigs.msgSendPoolSize * 2, 
			AppStaticConfigs.msgSendPoolSize * 2, 1L, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), new RejectedExecutionHandler() {
		
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			if (!executor.isShutdown()) {
				try {
					executor.getQueue().put(r);
				} catch (InterruptedException e) {
					logger.error(getClass().getSimpleName()+"fixedThreadPool2　 进程异常");
					e.printStackTrace();
				}
			}
		}
	});
	
	public MsgResendTask(SmsClient client) {
		this.client = client;
	}

	@Override
	public void run() {
		
		logger.info("短信重发任务启动!");
		
		while (isKeepGoing() && !this.isInterrupted()) {
			
			if (client.testConnectableNow(false)) {
				
				fixedThreadPool1.execute(new Runnable() {
					
					@Override
					public void run() {
						
						List<MtSms> list = MtTmpStore.getOutTimes(TIME_INTEVAL);
						
						if (!list.isEmpty()) {
							for (MtSms mtSms:list) {
								
								int times = mtSms.getiSendTimes();
								
								if (times <= 3) {
									
									fixedThreadPool2.execute(new Runnable() {
										
										@Override
										public void run() {
											
											Submit2 submit = Submit2.build(mtSms.getMobileno(), mtSms.getSrvNode(), mtSms.getServiceCode(), 
													mtSms.getSendport(), 1, Constant.MessageCodingE.GBK.getValue(), 
													Constant.MessageTypeE.SMS.getValue(), mtSms.getContent(), mtSms.getClientname(), mtSms.getOldserialnos());
											Head head = Head.build(submit.length(), CommandID.SGIP_SUBMIT2, mtSms.getCoderule(), mtSms.getDatetime(), mtSms.getSeqnumber());
											
											Message message = new Message(head, submit);
											
											boolean status = client.sendMsg(message);
											
											if (!status) {
												client.testConnectableNow(true);
											}
											
											logger.info("重发短信:" + message.toString() + ",状态:" + (status == true ? "提交成功" : "提交失败"));
										}
									});
								} else {
									logger.warn("短信发送失败,重发超过3次:" + mtSms.toString());
									MtTmpStore.remove(mtSms.getSerialno());
								}
							}
							toSleep = false;
						} else {
							toSleep = true;
						}
					}
				});
			} else {
				logger.warn("[短信重发任务]目标地址:" + client.getServerIp() + ":" + client.getServerPort() + "不通!");
				toSleep = true;
			}
			
			try {
				if (toSleep) {
					Thread.sleep(timeToSleep);
				}
			} catch (InterruptedException e) {}
		}
		
		if (fixedThreadPool1 != null && !fixedThreadPool1.isShutdown()) {
			fixedThreadPool1.shutdown();
		}
		
		if (fixedThreadPool2 != null && !fixedThreadPool2.isShutdown()) {
			fixedThreadPool2.shutdown();
		}
		
		logger.info("短信重发任务退出!");
	}
	
	public SmsClient getClient() {
		return client;
	}

	public boolean isKeepGoing() {
		return keepGoing;
	}

	public void setKeepGoing(boolean keepGoing) {
		this.keepGoing = keepGoing;
	}

	@Override
	public void destroy() {
		this.setKeepGoing(false);
	}

}
